using System;
using System.Collections.Generic;
using System.Linq;

namespace DependencyAnalysis.Algorithms.SubstringDetection
{
    public class Node
    {
        public SuffixTree Tree { get; private set; }
        public Node SuffixNode { get; set; }
        private readonly IDictionary<char, Edge> _edges;
        private Edge[] _edgesTemp;
        private readonly int _nodeNumber;

        public char this[int index]
        {
            get { return Tree.Text[index]; }
        }

        public Node(SuffixTree tree, Node suffixNode)
        {
            Tree = tree;
            SuffixNode = suffixNode;
            _edges = new Dictionary<char, Edge>();
            _nodeNumber = Tree.CreateNewNodeNumber();
        }

        public void AddEdge(int index, Edge edge)
        {
            _edges.Add(Tree.Text[index], edge);
            _edgesTemp = null;
        }

        public void RemoveEdge(int index)
        {
            _edges.Remove(Tree.Text[index]);
            _edgesTemp = null;
        }

        public Edge FindEdge(char ch)
        {
            Edge result;
            _edges.TryGetValue(ch, out result);
            return result;
        }

        public Edge[] GetEdges()
        {
            return _edgesTemp ?? (_edgesTemp = _edges.Values.ToArray());
        }


        public override int GetHashCode()
        {
            return _nodeNumber;
        }


        public override bool Equals(Object obj)
        {
            if (this == obj)
                return true;
            if (obj == null)
                return false;

            Node node = (Node)obj;
            return _nodeNumber == node._nodeNumber;
        }
    }
}